# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import uuid

from django.core.paginator import Paginator
from django.db import models


class BaseModule(models.Model):
    create_time = models.DateField(auto_now_add=True)
    update_time = models.DateField(auto_now=True)
    is_delete = models.BooleanField(default=False)

    class Meta:
        abstract = True


# 类别
class Category(BaseModule):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False)
    name = models.CharField(max_length=50, unique=True)
    is_show = models.BooleanField(default=True)

    def __unicode__(self):
        return u'%s' % self.id


# 标签类
class Tag(BaseModule):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False)
    name = models.CharField(max_length=50, unique=True)
    is_show = models.BooleanField(default=True)

    def __unicode__(self):
        return u'%s' % self.id


# 文章类
class Post(BaseModule):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False)
    title = models.CharField(max_length=50)
    desc = models.CharField(max_length=512)
    content = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING),
    tags = models.ManyToManyField(Tag)
    is_show = models.BooleanField(default=True)

    def __unicode__(self):
        return u'%s' % self.id

    @staticmethod
    def get_posts_by_page(num, per_page=1):
        num = int(num)
        pagintor = Paginator(Post.objects.order_by('-modified').all(), per_page)
        if num < 1:
            num = 1
        if num > pagintor.num_pages:
            num = pagintor.num_pages
        page = pagintor.page(num)

        pervious = 2
        last = 2
        if num <= pervious:
            start = 1
            end = last + pervious + 1
        if num > pervious:
            start = num - pervious + 1
            end = num + last + 1
        if end > pagintor.num_pages:
            min = end - pagintor.num_pages
            end = pagintor.num_pages
            start -= min
            if start <= 1:
                start = 1
        # pagintor.page_range
        return (page, range(start, end + 1))
# p = Post()
# p.tags.all()
